/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package repositoriodistribuido;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Vector;
import nanoxml.XMLElement;

/**
 *
 * @author ylopez
 */
public class drepCommandsImpl extends java.rmi.server.UnicastRemoteObject implements drepCommands {

    private static String currentDirectory;
    private static dmonCommands c;

    public drepCommandsImpl( ) throws java.rmi.RemoteException {
        super();
    }

    public static void setCurrentDirectory(String currentDirectory){
        drepCommandsImpl.currentDirectory = currentDirectory;
    }

    public static void setDmon(dmonCommands c){
        drepCommandsImpl.c = c;
    }

    public static String[] ldir() throws RemoteException {
        File dir = new File(currentDirectory);
        File[] files = dir.listFiles();
        int i = 0;
        String[] namesSizesFiles = null;

        if(files==null){
            System.out.println("No hay ficheros en el directorio especificado \n"+currentDirectory);
        }else {
            namesSizesFiles = new String[2*files.length];
            while(i<files.length){
                namesSizesFiles[2*i] = files[i].getName();
                namesSizesFiles[2*i+1] = Long.toString(files[i].length());
                i++;
            }
        }
        return namesSizesFiles;
    }

    public static void cat(String path) throws RemoteException {
        try {
            FileReader fr;
            BufferedReader bf;
            String line = "";

            fr = new FileReader(path);
            bf = new BufferedReader(fr);
            System.out.println("Inicio ejecuci'on cat:");
            while ((line = bf.readLine())!=null) {
                System.out.print(line+"\n");
            }
            System.out.println("Final ejecuci'on cat\n");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String[] con() throws RemoteException {
        String[] msj = new String[]{""};
        int aux = 0;
        try{
            aux = drepCommandsImpl.c.nops().length;
        }catch (RemoteException re){
            msj[0] = "No hay conexion con el dmon monitor";
            return msj;
        }
        msj[0] = "Si hay conexion con el dmon monitor";
        return msj;
    }

    public void connectionDrep(String userName, Date time) throws RemoteException {
        drepCommandsImpl.c.addUser(userName, time);
    }

    public String[] rdir() throws RemoteException {
        String[] namesSizesFiles = null;
        namesSizesFiles = ldir();
        return namesSizesFiles;
    }

    public String[] tuser() throws RemoteException {
        String[] users = null;
        users =  drepCommandsImpl.c.tuser();
        return users;
    }

    public String[] nrep() throws RemoteException {
        String[] result = null;
        result = new String[1];
        result[0] = Integer.toString(drepCommandsImpl.c.nrep());
        return result;

    }

    public void disconnectDrep(String user) throws RemoteException {
        c.remove(user);
    }

    public static void printResoults(String flag, String[] results){
        System.out.println("Inicio ejecuci'on "+ flag +":");
        if (flag.equals("ldir") || flag.equals("rdir") || flag.equals("tuser")) {
            for (int i = 0; i < results.length; i += 2) {
                System.out.println(results[i] + " " + results[i+1]);
            }
        }
        if (flag.equals("nrep")) {
            System.out.println("N'umero de repositorios: " + results[0]);
        }

        if (flag.equals("sube") || flag.equals("baja")) {
            System.out.println("Estatus de sube: " + results[0]);
        }

        if (flag.equals("con")) {
            System.out.println(results[0]);
        }
        System.out.println("Final ejecuci'on "+ flag +".");
    }

    public byte[] downloadFile(String fileName) throws RemoteException {
        try {
            File file = new File(currentDirectory+"/"+fileName);
            byte buffer[] = new byte[(int)file.length()];
            BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
            input.read(buffer,0,buffer.length);
            input.close();
            c.download();
            return(buffer);
        } catch(Exception e){
            System.out.println("FileImpl: "+e.getMessage());
            e.printStackTrace();
            return(null);
        }
    }

    public boolean existFile(String fileName) throws RemoteException {
        File file = new File(currentDirectory+"/"+fileName);
        boolean existFile = false;

        if (file.exists()){
            existFile = true;
        }

        return existFile;
    }

    public String sendFile(String fileName, byte buffer[]) throws RemoteException {
        try {
            FileOutputStream fos = new FileOutputStream(currentDirectory+"/"+fileName);
            BufferedOutputStream output = new BufferedOutputStream(fos);
            output.write(buffer,0,buffer.length);
            output.flush();
            output.close();
            c.upload();
            return "OK";
        } catch(Exception e) {
            System.err.println("Error en baja: "+ e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static String[] getParameter(String file) throws FileNotFoundException, IOException{
        String[] valuesForParameter;
        XMLElement xml = new XMLElement();
        FileReader reader = new FileReader(file);
        xml.parseFromReader(reader);
        Vector<XMLElement> parameters = xml.getChildren();

        valuesForParameter = new String[parameters.size()];
        valuesForParameter[0] = "vacio";
        valuesForParameter[1] = "vacio";
        valuesForParameter[2] = "vacio";
        valuesForParameter[3] = "vacio";
        valuesForParameter[4] = "vacio";

        for (XMLElement parameter : parameters) {
            if (parameter.getName().equals("nombre")) {
                valuesForParameter[0] = parameter.getContent();
            }
            if (parameter.getName().equals("hostserv")) {
                valuesForParameter[1] = parameter.getContent();
            }
            if (parameter.getName().equals("puertoserv")) {
                valuesForParameter[2] = parameter.getContent();
            }
            if (parameter.getName().equals("puertocli")) {
                valuesForParameter[3] = parameter.getContent();
            }
            if (parameter.getName().equals("directorio")) {
                valuesForParameter[4] = parameter.getContent();
            }
        }

        return valuesForParameter;
    }

}
